<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row>
        <el-col :sm="18">
          <el-input
            v-model="listQuery.username"
            placeholder="请输入用户名"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
          <el-select
            v-model="listQuery.roleId"
            placeholder="角色"
            clearable
            style="width: 90px"
            class="filter-item"
          >
            <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
          <el-button
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
          >{{ $t('table.search') }}</el-button>
        </el-col>
        <el-col :sm="6">
          <div class="sg-table-top-right-box">
            <el-button
              v-waves
              :loading="exportLoading"
              class="filter-item"
              type="primary"
              icon="el-icon-download"
              @click="handleExport"
            >{{ $t('table.export') }}</el-button>
            <el-button
              class="filter-item"
              style="margin-left: 10px;"
              type="primary"
              icon="el-icon-edit"
              @click="handleCreate"
            >{{ $t('table.add') }}</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      stripe
      border
      fit
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="用户名" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" class="sg-table-column-image">
        </template>
      </el-table-column>
      <el-table-column label="角色" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.sort')" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.actions')"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <el-button-group>
            <el-button size="mini" type="primary" @click="handleUpdate(row)">{{ $t('table.edit') }}</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(row, 'deleted')"
            >{{ $t('table.delete') }}</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="dialogTitleMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="model"
        label-position="left"
        label-width="70px"
      >
        <el-row>
          <el-col :span="18" :offset="3">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="model.username"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="3">
            <el-form-item label="密码">
              <el-input v-model="model.password" :placeholder="dialogStatus == 'update' ? '不修改请留空' : ''"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="3">
            <el-form-item label="角色">
              <el-select
                v-model="model.vue_admin_role_id"
                placeholder="角色"
                clearable
                style="width: 90px"
                class="filter-item"
              >
                <el-option
                  v-for="item in roles"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="3">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="model.sort"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button
          type="primary"
          @click="dialogStatus==='create'?createData():updateData()"
        >{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { showStatusFilter } from "@/filters/index";
import {
  fetchList,
  createModel,
  updateModel,
  deleteModel
} from "@/api/admin-users";
import { fetchAll } from "@/api/admin-roles";
import waves from "@/directive/waves"; // waves directive
import { parseTime, formatDate } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

export default {
  name: "AdminUser",
  components: { Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {
      tableKey: 0,
      modelName: "管理员",
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        roleId: undefined,
        sort: "+id"
      },
      roles: [],
      showOptions: [{ key: "1", value: "显示" }, { key: "2", value: "不显示" }],
      initModel: {
        id: undefined,
        username: "",
        password: "",
        avatar: "",
        sort: 0,
        vue_admin_role_id: undefined
      },
      model: {},
      dialogFormVisible: false,
      dialogStatus: "",
      rules: {
        username: [{ required: true, message: "用户名必填", trigger: "blur" }]
      },
      exportLoading: false,
      exportHeader: ["id", "username", "password", "avatar", "sort"]
    };
  },
  computed: {
    dialogTitleMap: function() {
      return {
        update: "编辑" + this.modelName,
        create: "创建" + this.modelName
      };
    }
  },
  created() {
    this.resetModel();
    this.getList();
    this.getRoles();
  },
  methods: {
    getRoles() {
      this.listLoading = true;
      fetchAll().then(response => {
        if (response.data.code === 20000) {
          let data = response.data;
          this.roles = data.data;
        }
      });
    },
    getList() {
      this.listLoading = true;
      fetchList(this.listQuery).then(response => {
        this.listLoading = false;
        if (response.data.code === 20000) {
          let data = response.data;
          this.list = data.data.data;
          this.total = data.data.total;
        }
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetModel() {
      this.model = Object.assign({}, this.initModel);
    },
    handleCreate() {
      this.resetModel();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          createModel(this.model).then(response => {
            this.dialogFormVisible = false;
            if (response.data.code === 20000) {
              this.$notify({
                title: "成功",
                message: "创建成功",
                type: "success",
                duration: 2000
              });
              this.getList();
            }
          });
        }
      });
    },
    handleUpdate(row) {
      this.model = Object.assign({}, row);
      this.model.password = undefined;
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const modelData = Object.assign({}, this.model);
          updateModel(modelData).then(response => {
            this.dialogFormVisible = false;
            if (response.data.code === 20000) {
              for (const v of this.list) {
                if (v.id === this.model.id) {
                  const index = this.list.indexOf(v);
                  this.list.splice(index, 1, this.model);
                  break;
                }
              }
              this.$notify({
                title: "成功",
                message: "更新成功",
                type: "success",
                duration: 2000
              });
            }
          });
        }
      });
    },
    handleDelete(row) {
      this.$confirm("删除后将不可恢复", "确定要删除吗？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteModel({ id: row.id }).then(response => {
          this.dialogFormVisible = false;
          if (response.data.code === 20000) {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
            const index = this.list.indexOf(row);
            this.list.splice(index, 1);
          }
        });
      });
    },
    handleExport() {
      this.exportLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = this.exportHeader;
        const filterVal = this.exportHeader;
        const data = this.formatJson(filterVal, this.list);
        const filename =
          this.modelName + "列表" + formatDate(new Date(), "yyyy-MM-dd");
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: filename
        });
        this.exportLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "show") {
            return showStatusFilter(v[j]);
          } else {
            return v[j];
          }
        })
      );
    }
  }
};
</script>
<style lang="scss" scoped>
.sg-table-column-image {
  width: 30px;
  height: auto;
}
</style>
